import thostmduserapi as mdapi
from basic_params import *
import time
import datetime


def pack_md(pDepthMarketData):
    return [
        pDepthMarketData.InstrumentID,

        round(pDepthMarketData.AskPrice1, 2),
        pDepthMarketData.AskVolume1,
        round(pDepthMarketData.BidPrice1, 2),
        pDepthMarketData.BidVolume1,

        round(pDepthMarketData.AskPrice2, 2),
        pDepthMarketData.AskVolume2,
        round(pDepthMarketData.BidPrice2, 2),
        pDepthMarketData.BidVolume2,

        round(pDepthMarketData.AskPrice3, 2),
        pDepthMarketData.AskVolume3,
        round(pDepthMarketData.BidPrice3, 2),
        pDepthMarketData.BidVolume3,

        round(pDepthMarketData.AskPrice4, 2),
        pDepthMarketData.AskVolume4,
        round(pDepthMarketData.BidPrice4, 2),
        pDepthMarketData.BidVolume4,

        round(pDepthMarketData.AskPrice5, 2),
        pDepthMarketData.AskVolume5,
        round(pDepthMarketData.BidPrice5, 2),
        pDepthMarketData.BidVolume5,

        round(pDepthMarketData.LastPrice, 2),
        pDepthMarketData.OpenInterest,
        int(pDepthMarketData.Volume),
        round(pDepthMarketData.Turnover, 2),
        round(pDepthMarketData.HighestPrice, 2),
        round(pDepthMarketData.LowestPrice, 2),
        pDepthMarketData.UpdateTime,
        pDepthMarketData.TradingDay]


class CFtdcMdSpi(mdapi.CThostFtdcMdSpi):
    def __init__(self, tapi):
        print('CFtdcMdSpi init starts')
        mdapi.CThostFtdcMdSpi.__init__(self)
        self.login_ErrorID = None
        self.sub_ErrorID = None
        self.tapi = tapi
        self.filter_flag = True

    def OnFrontConnected(self):
        # 一连接上就请求登录
        print("*连接到md服务器*")
        md_login_params = mdapi.CThostFtdcReqUserLoginField()
        md_login_params.BrokerID = BROKERID
        md_login_params.UserID = USERID
        md_login_params.Password = PASSWORD
        md_login_params.UserProductInfo = UserProductInfo
        self.tapi.ReqUserLogin(md_login_params, 0)

    def OnRspUserLogin(self, pRspUserLogin, pRspInfo, nRequestID, bIsLast):
        print(
            f"MDOnRspUserLogin响应用户登录中, SessionID会话id={pRspUserLogin.SessionID},ErrorID错误id={pRspInfo.ErrorID},ErrorMsg={pRspInfo.ErrorMsg}")
        self.login_ErrorID = pRspInfo.ErrorID
        if pRspInfo.ErrorID == 0:

            split = [Basic_var.excg_instrID_list[i:i+50]
                     for i in range(0, len(Basic_var.excg_instrID_list), 50)]
            for id in split:
                self.tapi.SubscribeMarketData(
                    [i.split('.')[1].encode('utf-8') for i in id], len(id))

    def OnRtnDepthMarketData(self, pDepthMarketData):
        if Basic_var.time_flag:
            md = pack_md(pDepthMarketData)
            Basic_var.receive_data_Que.put(md)
        else:
            pass

    def OnRspSubMarketData(self, pSpecificInstrument: 'CThostFtdcSpecificInstrumentField', pRspInfo: 'CThostFtdcRspInfoField', nRequestID: 'int', bIsLast: 'bool') -> "void":
        pass
        #print(f"OnRspSubMarketData:{pSpecificInstrument.InstrumentID} success")

    def OnFrontDisconnected(self, nReason):
        print(datetime.datetime.today(), 'disconnected')


def mduserapi_prepare():
    if Basic_var.Trading_day:
        print('mduserapi_prepare starts')
        mduserapi = mdapi.CThostFtdcMdApi_CreateFtdcMdApi()
        mduserspi = CFtdcMdSpi(mduserapi)
        mduserapi.RegisterFront(md_FrontAddr)
        mduserapi.RegisterSpi(mduserspi)
        return mduserapi, mduserspi


def connect_md():
    if Basic_var.Trading_day:
        Basic_var.mduserapi, Basic_var.mduserspi = mduserapi_prepare()
        Basic_var.mduserapi.Init()
        time.sleep(Basic_var.keep_connect_seconds)
        Basic_var.mduserapi.Release()
        print('ctp接口释放')


def end_receive():
    if Basic_var.Trading_day:
        Basic_var.receive_data_Que.put(False)
